package helper

import (
	"encoding/json"
	"net/http"
	"net/url"
	"strings"
)

// ParsePostRawData 解析post原生数据
func ParsePostRawData(raw string, parse interface{}) interface{} {
	raw = Trim(raw)
	if len(raw) > 0 {
		if raw[0] == '{' {
			if parse == nil {
				parse = map[string]interface{}{}
			}
			if err := json.Unmarshal([]byte(raw), &parse); err != nil {
				parse = nil
			}
		} else if vals, err := url.ParseQuery(raw); err == nil {
			data := map[string]string{}
			for k, v := range vals {
				data[k] = v[0]
			}
			return data
		} else {
			parse = nil
		}
		return parse
	}
	return nil
}

// FormatRequestURL 格式化uri
func FormatRequestURL(h *http.Request) *url.URL {
	if h.URL.Host != "" {
		return h.URL
	}
	r, _ := url.Parse(GetNowFullURL(h))
	return r
}

// GetNowFullURL 获取当前完整url
func GetNowFullURL(h *http.Request) string {
	fullurl := h.Host + h.RequestURI
	if !strings.HasPrefix(fullurl, "http") {
		if h.TLS == nil {
			fullurl = "http://" + fullurl
		} else {
			fullurl = "https://" + fullurl
		}
	}
	return fullurl
}
